#include <pace/P99Component.h>
#include <pace/MsgTubeI.h>
#include "DataAccess.h"

#include <cstdlib>

#include "WatchEventHandlerI.h"

#define SLEEP 25000 // 25 ms

using namespace std;
using namespace iPlature;
using namespace Monitor;

class WebTagQueue : public P99Component
{
public:
  void PostInitCall()
  {
    LOG log(__FUNCTION__);
    const string serverName = "WebTagQueue";

    Ice::PropertiesPtr icePropPtr = Component::instance()->properties();
    log.Info() << "## 0. 项目配置初始化成功" << endl;

    CDataAccess::GetInstance()->Initialize();
    log.Info() << "## 1. 数据库连接池初始化成功" << endl;

    WatchWithDataInterfacePtr watchEvent = new CWatchEventHandlerI();
    this->subscribe("Tag/WatchWithDataTopic", watchEvent);
    log.Info() << "## 2. Tag 服务注册成功" << endl;

    const string fetchSql = "select ID, TAGNAME, TAGVALUE, TAGTYPE from UACS_WEB_TAG_QUEUE";
    while (true)
    {
      iDA::Command cmd(&CDataAccess::GetInstance()->m_DBCon, fetchSql);
      cmd.Execute();
      string ids = "(";
      string tagKey = "";
      string tagVal = "";
      string tagType = "";
      int count = 0;
      while (cmd.FetchNext())
      {
        count++;
        ids += cmd.Field(1).AsString() + ",";
        tagKey = cmd.Field(2).AsString();
        tagVal = cmd.Field(3).AsString();
        tagType = cmd.Field(4).AsString();
        if (tagType.compare("EV") == 0)
        {
          TAGVALUEMAP tagTimeStamp;
          Tag::GetInst().EventPut(tagTimeStamp, tagKey, tagVal);
        }
        else if (tagType.compare("MD") == 0 || tagType.compare("L1OPC") == 0)
        {
          TAGVALUEMAP tagTimeStamp;
          TAGVALUEMAP tagValueMap;
          tagValueMap.insert(map<string, string>::value_type(tagKey, tagVal));
          Tag::GetInst().MDPut(tagTimeStamp, tagValueMap);
        }
      }
      if (count == 0)
      {
        usleep(SLEEP);
        continue;
      }
      ids.resize(ids.size() - 1);
      ids += ")";
      const string delSql = "delete from UACS_WEB_TAG_QUEUE where ID in " + ids ;//"//+ ";";
      iDA::Command cmd2(&CDataAccess::GetInstance()->m_DBCon, delSql);
      cmd2.Execute();
      //cmdDel.Execute();
//	 cnnPtr.get()->Commit();
    }
  }

  ByteSeq HandleMessage(const ByteSeq &ParamBuffer)
  {
    return ParamBuffer;
  }
};

PACE_SERVER_INSTALL(WebTagQueue);
